package com.lingxu.module.modelScore.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lingxu.base.common.api.vo.Result;
import com.lingxu.module.modelScore.entity.ModelScoreBase;
import com.lingxu.module.modelScore.entity.ModelScoreVO;
import com.lingxu.module.modelScore.entity.RunSum;
import com.lingxu.module.modelScore.mapper.ModelScoreBaseMapper;
import com.lingxu.module.modelScore.service.ModelScoreBaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Title: ModelScoreBaseServiceImpl
 * @Package: com.ptmh.module.modelScore.service.impl
 * @Author: ysj闫世杰
 * @Email: 1105324813@qq.com
 * @Date: Created in 2023/11/29 16:13
 * @Description:
 * @Version: 1.0.0
 */
@Slf4j
@Service
public class ModelScoreBaseServiceImpl extends ServiceImpl<ModelScoreBaseMapper, ModelScoreBase>
        implements ModelScoreBaseService {

    @Autowired
    private ModelScoreBaseMapper modelScoreBaseMapper;

    /**
     * @Author ysj闫世杰
     * @Description 新增评分标准
     * @Date 2023/11/29 16:30
     * @Param: scoreBase
     * @return com.ptmh.base.common.api.vo.Result
     **/
    @Override
    public Result addModelScoreBase(ModelScoreBase scoreBase) {
        try {
            scoreBase.setCreateTime(new Date());
            modelScoreBaseMapper.insert(scoreBase);
            return Result.ok("操作成功");
        }catch (Exception e){
            log.error("操作异常",e);
            return Result.error("操作异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 修改评分标准
     * @Date 2023/11/29 17:01
     * @Param: scoreBase
     * @return com.ptmh.base.common.api.vo.Result
     **/
    @Override
    public Result updateModelScoreBase(List<ModelScoreBase> scoreBase) {
        try {
            Date date = new Date();
            for(ModelScoreBase m : scoreBase) {
                m.setUpdateTime(date);
                modelScoreBaseMapper.updateById(m);
            }
            return Result.ok("操作成功");
        }catch (Exception e){
            log.error("操作异常",e);
            return Result.error("操作异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 查询评分标准
     * @Date 2023/11/29 17:12
     * @Param:
     * @return com.ptmh.base.common.api.vo.Result
     **/
    @Override
    public Result findModelScoreBase() {
        try {
            List<ModelScoreVO> list = modelScoreBaseMapper.findModelScoreBase();
            return Result.ok(list,"查询成功");
        }catch (Exception e){
            log.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }


    /**
     * @Author ysj闫世杰
     * @Description 处理计算模型
     * 算法说明：
     * 1、模型总分100，分三大类占比，总得分 = 模型复杂度 + 模型应用量 + 成效反馈
     * 2、三大类对应其下小类，小类的总分为大类占比分数（100 * 20% * 20%）
     * 3、例：
     *       模型复杂度占比20%   20分
     *       表数量占比20%       4分，一个表为1分，>= 4 为满分
     *       成效反馈得分的条件为审批通过记录
     * @Date 2023/12/8 9:08
     * @Param:
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result startModelScoreHandler(String id) {
        try {
            //查询所有模型
            //查询评分规则
            List<ModelScoreVO> list = modelScoreBaseMapper.findModelScoreBase();
            List<String> masterModel =  modelScoreBaseMapper.findAllModel(id);
            for(String masterId : masterModel) {
                //各个规则分数占比
                //模型复杂度
                BigDecimal mxfzd = mxfzdHandler(list,masterId);
                //模型应用量
                BigDecimal mxyy = mxyyHandler(list,masterId);
                //成效反馈
                BigDecimal cxfk = cxfkHandler(list,masterId);
                BigDecimal result = mxfzd.add(mxyy).add(cxfk);
                //按照主模型id更新模型表模型分数
                modelScoreBaseMapper.updateModelScore(masterId,result);
            }
            return Result.ok("操作成功");
        }catch (Exception e){
            log.error("操作异常",e);
            return Result.error("操作异常");
        }
    }


    //模型复杂度
    private BigDecimal mxfzdHandler(List<ModelScoreVO> list,String masterId) {
        BigDecimal result;
        //占比分数
        BigDecimal scoreWeight = list.get(0).getScoreWeight();
        List<ModelScoreVO> child = list.get(0).getModelScoreVOList();
        BigDecimal bsl = new BigDecimal("0");
        BigDecimal zmxsl = new BigDecimal("0");
        BigDecimal mxsz = new BigDecimal("0");
        for(ModelScoreVO vo : child){
            if("表数量".equals(vo.getScoreName())){
                BigDecimal weight = vo.getScoreWeight();
                BigDecimal zb = scoreWeight.multiply(weight.divide(new BigDecimal("100"),1));
                //查询表数量
                BigDecimal table = modelScoreBaseMapper.findTableCount(masterId);
                if(table.compareTo(zb) >= 0){
                    bsl = zb;
                }else {
                    bsl = table;
                }
            }
            if("子模型数量".equals(vo.getScoreName())){
                BigDecimal weight = vo.getScoreWeight();
                BigDecimal zb = scoreWeight.multiply(weight.divide(new BigDecimal("100"),1));
                //查询子模型数量
                BigDecimal model = modelScoreBaseMapper.findModelCount(masterId);
                if(model.compareTo(zb) >= 0){
                    zmxsl = zb;
                }else {
                    zmxsl = model;
                }
            }
            if("算子数量".equals(vo.getScoreName())){
                BigDecimal weight = vo.getScoreWeight();
                BigDecimal zb = scoreWeight.multiply(weight.divide(new BigDecimal("100"),1));
                //查询模型算子数量
                BigDecimal model = modelScoreBaseMapper.findModelOperator(masterId);
                if(model.compareTo(zb) >= 0){
                    mxsz = zb;
                }else {
                    mxsz = model;
                }
            }
        }
        result = bsl.add(zmxsl).add(mxsz);
        return result;
    }

    //模型应用量
    private BigDecimal mxyyHandler(List<ModelScoreVO> list,String masterId) {
        BigDecimal result;
        BigDecimal bdq = new BigDecimal("0");
        BigDecimal fbdq = new BigDecimal("0");
        BigDecimal scsl = new BigDecimal("0");
        BigDecimal bdwtsl = new BigDecimal("0");
        //查询模型所在地区
        String area = modelScoreBaseMapper.findModelArea(masterId);
        //占比分数
        BigDecimal scoreWeight = list.get(1).getScoreWeight();
        List<ModelScoreVO> child = list.get(1).getModelScoreVOList();
        for(ModelScoreVO vo : child){
            if("本地区使用次数".equals(vo.getScoreName())){
                BigDecimal weight = vo.getScoreWeight();
                BigDecimal zb = scoreWeight.multiply(weight.divide(new BigDecimal("100"),1));
                //查询本地区克隆模型id
                List<String> cloneModelIds = modelScoreBaseMapper.findCloneModelIds(masterId,area,"1");
                //本身linkmodelid
                List<String> linkModelId = modelScoreBaseMapper.findLinkModelId(masterId);
                List<String> ids = new ArrayList<>(linkModelId);
                for(String s : cloneModelIds){
                    String[] split = s.split(",");
                    ids.addAll(Arrays.asList(split));
                }
                //查询运行次数
                BigDecimal count = modelScoreBaseMapper.findAreaUseCount(ids);
                if(count.compareTo(zb) >= 0){
                    bdq = zb;
                }else {
                    bdq = count;
                }
            }
            if("非本地区使用次数".equals(vo.getScoreName())){
                BigDecimal weight = vo.getScoreWeight();
                BigDecimal zb = scoreWeight.multiply(weight.divide(new BigDecimal("100"),1));
                //查询非本地区克隆模型id
                List<String> cloneModelIds = modelScoreBaseMapper.findCloneModelIds(masterId,area,"0");
                List<String> ids = new ArrayList<>();
                for(String s : cloneModelIds){
                    String[] split = s.split(",");
                    ids.addAll(Arrays.asList(split));
                }
                //查询运行次数
                BigDecimal count = modelScoreBaseMapper.findAreaUseCount(ids);
                if(count.compareTo(zb) >= 0){
                    fbdq = zb;
                }else {
                    fbdq = count;
                }
            }
            if("上传之后数据量".equals(vo.getScoreName())){
                BigDecimal weight = vo.getScoreWeight();
                BigDecimal zb = scoreWeight.multiply(weight.divide(new BigDecimal("100"),1));
                List<ModelScoreVO> modelScoreVOList = vo.getModelScoreVOList();
                BigDecimal mfSum = modelScoreVOList.get(0).getScoreWeight();
                //本身linkmodelid
                List<String> linkModelId = modelScoreBaseMapper.findLinkModelId(masterId);
                List<String> ids = new ArrayList<>(linkModelId);
                //查询上传总量
                BigDecimal counts = modelScoreBaseMapper.findModelDataCounts(ids);
                if(counts.compareTo(mfSum) >= 0){
                    scsl = zb;
                }else {
                    //上传量 / 满分总量 * 占比分数
                    scsl = counts.divide(mfSum,1).multiply(zb);
                }
            }
            if("比对问题数据量".equals(vo.getScoreName())){
                BigDecimal weight = vo.getScoreWeight();
                BigDecimal zb = scoreWeight.multiply(weight.divide(new BigDecimal("100"),1));
                List<ModelScoreVO> modelScoreVOList = vo.getModelScoreVOList();
                BigDecimal mfSum = modelScoreVOList.get(0).getScoreWeight();
                //本身linkmodelid
                List<String> linkModelId = modelScoreBaseMapper.findLinkModelId(masterId);
                List<String> ids = new ArrayList<>(linkModelId);
                //计算比对问题数据量
                int sum = 0;
                for(String id : ids){
                    //按照模型id查询所有的运行记录
                    List<RunSum> runSumList = modelScoreBaseMapper.findModelRunList(id);
                    //按total和colums字段去重复计算和
                    Set<RunSum> sumSet = new TreeSet<>(Comparator.comparing(i -> (i.getResulttotal() + "" + i.getResultcolumns())));
                    sumSet.addAll(runSumList);
                    List<RunSum> newSumList = new ArrayList<>(sumSet);
                    for(RunSum run : newSumList){
                        sum += run.getResulttotal();
                    }
                }

                BigDecimal bdSum = new BigDecimal(sum);
                if(bdSum.compareTo(mfSum) >= 0){
                    bdwtsl = zb;
                }else {
                    //问题量 / 满分总量 * 占比分数
                    bdwtsl = bdSum.divide(mfSum,1).multiply(zb);
                }
            }
        }
        result = bdq.add(fbdq).add(scsl).add(bdwtsl);
        return result;
    }

    //成效反馈
    private BigDecimal cxfkHandler(List<ModelScoreVO> list,String masterId) {
        BigDecimal result;
        BigDecimal wtxs = new BigDecimal("0");
        BigDecimal lasl = new BigDecimal("0");
        BigDecimal xwxc = new BigDecimal("0");
        BigDecimal ldps = new BigDecimal("0");
        //占比分数
        BigDecimal scoreWeight = list.get(2).getScoreWeight();
        List<ModelScoreVO> child = list.get(2).getModelScoreVOList();
        for(ModelScoreVO vo : child){
            if("问题线索".equals(vo.getScoreName())){
                BigDecimal weight = vo.getScoreWeight();
                BigDecimal zb = scoreWeight.multiply(weight.divide(new BigDecimal("100"),1));
                //查询问题线索数量
                BigDecimal count = modelScoreBaseMapper.findResultFeedback(masterId,"1");
                if(count.compareTo(zb) >= 0){
                    wtxs = zb;
                }else {
                    wtxs = count;
                }
            }
            if("立案数量".equals(vo.getScoreName())){
                BigDecimal weight = vo.getScoreWeight();
                BigDecimal zb = scoreWeight.multiply(weight.divide(new BigDecimal("100"),1));
                //查询立案数量
                BigDecimal count = modelScoreBaseMapper.findResultFeedback(masterId,"2");
                if(count.compareTo(zb) >= 0){
                    lasl = zb;
                }else {
                    lasl = count;
                }
            }
            if("新闻宣传".equals(vo.getScoreName())){
                BigDecimal weight = vo.getScoreWeight();
                BigDecimal zb = scoreWeight.multiply(weight.divide(new BigDecimal("100"),1));
                //查询新闻宣传数量
                BigDecimal count = modelScoreBaseMapper.findResultFeedback(masterId,"3");
                if(count.compareTo(zb) >= 0){
                    xwxc = zb;
                }else {
                    xwxc = count;
                }
            }
            if("领导批示".equals(vo.getScoreName())){
                BigDecimal weight = vo.getScoreWeight();
                BigDecimal zb = scoreWeight.multiply(weight.divide(new BigDecimal("100"),1));
                //查询领导批示数量
                BigDecimal count = modelScoreBaseMapper.findResultFeedback(masterId,"4");
                if(count.compareTo(zb) >= 0){
                    ldps = zb;
                }else {
                    ldps = count;
                }
            }
        }
        result = wtxs.add(lasl).add(xwxc).add(ldps);
        return result;
    }
}
